package com.suray.wcs.service.wmsconnect;

import com.alibaba.fastjson.JSON;
import com.suray.basic.wcs.utils.LoggerUtil;
import com.suray.commin.core.utils.SpringContextHolder;
import com.suray.wcs.service.config.properties.WcsProperties;
import com.suray.wcs.service.core.util.HttpClientSpring;
import com.suray.wcs.service.enums.NetAddressType;
import com.suray.wcs.service.enums.NotificationTypeEnum;
import com.suray.wcs.service.hk.agv.bean.HkAgvTaskResponse;
import com.suray.wcs.service.hk.agv.bean.HkAgvTaskSend;
import com.suray.wcs.service.hk.agv.bean.HkNormalResponse;
import com.suray.wcs.service.hk.agv.bean.HkTaskContinue;
import com.suray.wcs.service.system.service.impl.NetAddressManageDBServiceImpl;
import com.suray.wcs.service.util.WcsUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ToHkAgv {
    private static Logger log = LoggerFactory.getLogger(ToHkAgv.class);

    private static NetAddressManageDBServiceImpl netAddressManageDBService =
            SpringContextHolder.getBean(NetAddressManageDBServiceImpl.class);

    final public static String sendTaskPath = "/rcms/services/rest/hikRpcService/genAgvSchedulingTask";
    final public static String taskContinuePath = "/rcms/services/rest/hikRpcService/continueTask";

    private static String getHkAgvPort() {
        return netAddressManageDBService.findNetAddressByType(NetAddressType.HK_AGV).get(0).getPort();
    }

    private static String getHkAgvIp() {
        return netAddressManageDBService.findNetAddressByType(NetAddressType.HK_AGV).get(0).getIp();
    }


    /**
     * 海康Agv任务发送
     * @param task
     * @return
     */
    public static boolean hkSendTask(HkAgvTaskSend task) {
        log.info("hkSendTask=>{}", JSON.toJSONString(task));
        String result = StringUtils.EMPTY;
        for (int i = 0; i < WcsProperties.ATTEMPT_NUM_3; i++) {
            try {
                result = HttpClientSpring.sendPostRequest(WcsUtil.getHttpUrl(getHkAgvIp(), getHkAgvPort(), sendTaskPath),
                        JSON.toJSONString(task));
                if (StringUtils.isNotBlank(result)) {
                    break;
                }
            } catch (Exception e) {
                log.info("exeTaskApply 接口异常：{}", e.getMessage(), e);
                WcsUtil.delay(1000);
            }
        }
        log.info("hkSendTask return data:{}", result);
        try {
            if (StringUtils.isBlank(result)) {
                return false;
            }
            HkAgvTaskResponse hkAgvTaskResponse = JSON.parseObject(result, HkAgvTaskResponse.class);

            if (!hkAgvTaskResponse.getReqCode().equals(task.getReqCode())) {
                String message = "任务继续时Agv回复的请求编号不一致:" + task;
                LoggerUtil.warn(message, ToHkAgv.class);
                WcsUtil.notification(message, NotificationTypeEnum.WARN);
                return false;
            }

            Integer returnStatus = Integer.valueOf(hkAgvTaskResponse.getCode());
            if (returnStatus == WcsProperties.SUCCESS) {
                log.info("Agv任务" + task + "下发成功！");
                return true;
            } else if (returnStatus == WcsProperties.FAIL) {
                log.error("Agv任务" + task + "下发失败！原因-->"
                        + hkAgvTaskResponse.getMessage() + ", "
                        + hkAgvTaskResponse.getData());
                WcsUtil.notification("Agv任务下发失败：" + task.getTaskCode(), NotificationTypeEnum.ERROR);
                return false;
            } else {
                log.error("状态码不存在,接收到为！" + returnStatus);
                return false;
            }
        } catch (Exception e) {
            WcsUtil.exceptionLog(e, ToHkAgv.class);
            log.error("任务申请接口解析返回值出现异常！{}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 海康Agv任务继续
     * @param taskContinue
     * @return
     */
    public static boolean hkSendTaskContinue(HkTaskContinue taskContinue) {
        log.info("hkSendTaskContinue=>{}", JSON.toJSONString(taskContinue));
        String result = StringUtils.EMPTY;
        for (int i = 0; i < WcsProperties.ATTEMPT_NUM_3; i++) {
            try {
                result = HttpClientSpring.sendPostRequest(WcsUtil.getHttpUrl(getHkAgvIp(), getHkAgvPort(), taskContinuePath),
                        JSON.toJSONString(taskContinue));
                if (StringUtils.isNotBlank(result)) {
                    break;
                }
            } catch (Exception e) {
                log.info("exeTaskApply 接口异常：{}", e.getMessage(), e);
                WcsUtil.delay(1000);
            }
        }
        log.info("hkSendTaskContinue return data:{}", result);
        try {
            if (StringUtils.isBlank(result)) {
                return false;
            }
            HkNormalResponse normalResponse = JSON.parseObject(result, HkNormalResponse.class);

            if (!normalResponse.getReqCode().equals(taskContinue.getReqCode())) {
                String message = "任务继续时Agv回复的请求编号不一致，任务编号为" + taskContinue.getTaskCode();
                LoggerUtil.warn(message, ToHkAgv.class);
                WcsUtil.notification(message, NotificationTypeEnum.WARN);
                return false;
            }

            Integer returnStatus = Integer.valueOf(normalResponse.getCode());
            if (returnStatus == WcsProperties.SUCCESS) {
                log.info("Agv任务继续" + taskContinue + "下发成功！");
                return true;
            } else if (returnStatus == WcsProperties.FAIL) {
                log.error("Agv任务继续" + taskContinue + "下发失败！原因-->"
                        + normalResponse.getMessage());
                WcsUtil.notification("Agv任务继续下发失败：" + taskContinue.getTaskCode(),
                        NotificationTypeEnum.ERROR);
                return false;
            } else {
                log.error("状态码不存在,接收到为！" + returnStatus);
                return false;
            }
        } catch (Exception e) {
            log.error("任务申请接口解析返回值出现异常！{}", e.getMessage(), e);
            return false;
        }
    }
}
